﻿using CSharpToolWPF.Pages;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using static CSharpToolWPF.Pages.PageAutoAddDenpendencies;
using WPFTools;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Automation.Peers;

namespace CSharpToolWPF.Windows {
    /// <summary>
    /// WindowInteractivelyFillBlank.xaml 的交互逻辑
    /// </summary>
    public partial class WindowInteractivelyFillBlank : Window {
        private ObservableCollection<ClassAndLibData> ListClassAndLib { get; set; }
        private List<ClassAndLibData> ListClassAndLibThatNeedFill {  get; set; }
        public class SearchResult {
            public SearchResult(string wholeLine, string catched) {
                WholeLine = wholeLine;
                Catched = catched;
            }
            public string WholeLine { get; set; }
            public string Catched { get; set; }
        }
        public ObservableCollection<SearchResult> Results { get; set; }
        private int index = 0;
        public WindowInteractivelyFillBlank(ObservableCollection<ClassAndLibData> listClassAndLib) {
            InitializeComponent();
            ListClassAndLib = listClassAndLib;
            ListClassAndLibThatNeedFill = listClassAndLib.Where(item=>string.IsNullOrEmpty(item.LibName)).ToList();
            Results = new ObservableCollection<SearchResult>();
            this.FontFamily = new FontFamily("Sarasa Term SC");
        }

        private void Window_Loaded(object sender, RoutedEventArgs e) {
            this.btnNext_Click(sender, e);
        }

        bool isInitial = true;
        private void btnNext_Click(object sender, RoutedEventArgs e) {
            // 反馈数据到原列表
            if (isInitial) {
                isInitial = false;
            }
            else {
                var target = ListClassAndLib.FirstOrDefault(item=>item.ClassName == tbCurrentSearch.Text);
                target.LibName = tbLibName.Text;
            }
            // 显示下一条搜索
            if(index == ListClassAndLibThatNeedFill.Count - 1) {
                btnNext.Visibility = Visibility.Collapsed;
                btnEnd.Visibility = Visibility.Visible;
            }
            if(index >= ListClassAndLibThatNeedFill.Count) {
                this.Close();
                return;
            }
            var currentClass = ListClassAndLibThatNeedFill[index++];
            tbCurrentSearch.Text = currentClass.ClassName;
            // 查找
            string headerPath = @"D:/VC/ObjectPRX 2024/inc";
            string pattern = $"class[\t ]+(\\w+)[\t ]+{currentClass.ClassName}\\b";
            var result = this.FindMatchesInHeaderFiles(headerPath, pattern);

            Results.Clear();
            result.ForEach(item => Results.Add(item));
            dataGridResults.ItemsSource = Results;
            if (Results.Count == 0) {
                tbLibName.Clear();
            }
            else {
                dataGridResults.SelectedIndex = 0;
            }
        }

        private void btnEnd_Click(object sender, RoutedEventArgs e) {
            var target = ListClassAndLib.FirstOrDefault(item => item.ClassName == tbCurrentSearch.Text);
            if (target != null) {
                target.LibName = tbLibName.Text;
            }
            this.Close();
        }

        // 使用一个静态字典来缓存文件内容，假设文件路径是唯一的
        private Dictionary<string, string[]> fileCache = new Dictionary<string, string[]>();

        // 可以使用文件系统监视器来检测文件是否发生变化（可选）
        private Dictionary<string, DateTime> fileLastWriteTime = new Dictionary<string, DateTime>();

        public List<SearchResult> FindMatchesInHeaderFiles(string directoryPath, string pattern) {
            var matchedResults = new List<SearchResult>();

            try {
                // 获取目录下的所有 .h 文件
                var headerFiles = Directory.GetFiles(directoryPath, "*.h", SearchOption.AllDirectories);

                foreach (var file in headerFiles) {
                    string[] lines;
                    bool fileChanged = false;

                    // 检查文件是否已经被缓存，并且文件自上次读取以来是否被修改过
                    if (fileCache.ContainsKey(file)) {
                        // 检查文件的最后修改时间
                        if (File.Exists(file)) {
                            var lastWriteTime = File.GetLastWriteTime(file);
                            if (fileLastWriteTime.ContainsKey(file) && lastWriteTime != fileLastWriteTime[file]) {
                                fileChanged = true;
                            }
                        }
                    }

                    // 如果文件未缓存或者文件已更改，则重新读取文件内容
                    if (!fileCache.ContainsKey(file) || fileChanged) {
                        lines = File.ReadAllLines(file);
                        fileCache[file] = lines;

                        // 更新文件的最后修改时间
                        if (File.Exists(file)) {
                            fileLastWriteTime[file] = File.GetLastWriteTime(file);
                        }
                    }
                    else {
                        // 从缓存中获取文件内容
                        lines = fileCache[file];
                    }

                    // 遍历文件内容并查找匹配项
                    for (int i = 0; i < lines.Length; i++) {
                        Match match = Regex.Match(lines[i], pattern);
                        if (match.Success) {
                            var result = new SearchResult(lines[i], match.Groups[1].Value);
                            matchedResults.Add(result);
                        }
                    }
                }
            }
            catch (Exception ex) {
                MessageBox.Show($"Error: {ex.Message}");
            }

            return matchedResults;
        }

        private void tbLibName_TextChanged(object sender, TextChangedEventArgs e) {
            
        }

        private void dataGridResults_Selected(object sender, RoutedEventArgs e) {
            var item = dataGridResults.SelectedItem as SearchResult;
            if (item == null) {
                return;
            }
            // 
            string pattern = @"AP\d+_\d+_\d+";
            var match = Regex.Match(item.Catched, pattern);
            if (match.Success) {
                string projectCode = match.Groups[0].Value;
                libNameDashRemoved = item.Catched.Remove(item.Catched.IndexOf(projectCode) + projectCode.Length, 1);
                // 移除后四个字符，也就是AP09_7_063_CreateBlocTransaction_Exp后面的_Exp
                libNameDashRemoved = libNameDashRemoved.Remove(libNameDashRemoved.Length- 4, 4);
            }
            else {
                libNameDashRemoved = item.Catched;
            }


            libNameWithDash = item.Catched;

            if (checkBoxIsDeleteLastDash.IsChecked.Value) {
                tbLibName.Text = libNameDashRemoved;
            }
            else {
                tbLibName.Text = libNameWithDash;
            }


            // 前面match成功了的话应该没什么错误了，所以如果搜索结果只有一个，直接自动下一步
            if (Results.Count == 1 && match.Success) {
                btnNext_Click(sender, e);
            }
        }

        //private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
        //    e.Cancel = true;
        //    this.Hide();
        //}

        string libNameDashRemoved;
        string libNameWithDash;
        private void checkBoxIsDeleteLastDash_Click(object sender, RoutedEventArgs e) {
            if (checkBoxIsDeleteLastDash.IsChecked.Value) {
                tbLibName.Text = libNameDashRemoved;
            }
            else {
                tbLibName.Text = libNameWithDash;
            }
        }
    }
}
